<?php
/**
 * Created by PhpStorm.
 * User: dev
 * Date: 5/9/14
 * Time: 3:18 PM
 */
class Terms extends Eloquent {

    public static $table = 'terms';
    public static $key = 'id';


    function __construct(){
        parent::__construct();
    }

    public static function location($postID, $last = false){
        if(!empty($postID) && $last == false){
            $l = DB::table('terms')
                ->where('term','=','location')
                ->where('post_id','=',$postID)
                ->order_by('id', 'DESC')
                ->get();
            return $l;
        }elseif (!empty($postID) && $last == true){
            $l = DB::table('terms')
                ->where('term','=','location')
                ->where('post_id','=',$postID)
                ->order_by('value','DESC')
                ->first();
            if(!empty($l)){
                return $l->value;
            }else{
                return 'null';
            }
        }
    }



    public static function category($postID, $last = false){
        if(!empty($postID) && $last == false){
            $l = DB::table('terms')
                ->where('term','=','category')
                ->where('post_id','=',$postID)
                ->order_by('id', 'DESC')
                ->get();
            return $l;
        }elseif (!empty($postID) && $last == true){
            $l = DB::table('terms')
                ->where('term','=','category')
                ->where('post_id','=',$postID)
                ->order_by('value','DESC')
                ->first();
            if(!empty($l)){
                return $l->value;
            }else{
                return 'null';
            }
            //return $l->value;
        }
    }

    public static function post($location,$category,$offset=0,$limit=10){
        if(empty($location) && !empty($category)){
            $sql = "SELECT P.* from post P
			INNER JOIN terms T on P.id = T.post_id and (T.term='category' or T.term='keyword')
			and T.value = $category
			and status='51' group by P.id Limit $offset,$limit";
            $result = DB::query($sql);

        }
        if(!empty($location) && !empty($category)){
            $sql = "SELECT P.* from post P
			INNER JOIN terms T on P.id = T.post_id
			AND (T.term='category' or T.term='keyword') and T.value = $category

			INNER JOIN terms T2 on P.id = T2.post_id
			AND (T2.term='location') and T2.value = $location and status='51'
			Limit $offset,$limit";
            $result = DB::query($sql);
        }
        if(!empty($location) && empty($category)){
            $sql = "SELECT P.* from post P
			INNER JOIN terms T on P.id = T.post_id
			AND (T.term='location') and T.value = $location
			Limit $offset,$limit";

            $result = DB::query($sql);
        }
     //   dd($sql);
        return $result;
    }


}